package com.sky.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery;
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if(employee.getStatus() == StatusConstant.DISABLE){
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }
    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        // 防止前端传入 id 影响自增策略
        employee.setId(null);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setStatus(StatusConstant.ENABLE);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        this.save( employee);
    }
    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //1.构建分页对象
        Page<Employee> page=new Page<>(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> res = lambdaQuery()
                .like(employeePageQueryDTO.getName() != null, Employee::getName, employeePageQueryDTO.getName())
                .orderByDesc(Employee::getCreateTime)
                .page(page);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(res.getTotal());
        pageResult.setRecords(res.getRecords());
        return pageResult;
    }
    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, String id) {
        Employee employee = employeeMapper.selectById(id);
        if(employee == null){
            throw new RuntimeException("员工不存在");
        }
        if(status == StatusConstant.ENABLE){
            employee.setStatus(StatusConstant.ENABLE);
        }
        if(status == StatusConstant.DISABLE){
            employee.setStatus(StatusConstant.DISABLE);
        }
        this.updateById(employee);
    }
    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        return employeeMapper.selectById(id);
    }
    /**
     * 编辑员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Long id = employeeDTO.getId();
        log.info("待修改员工id：{}", id);
        Employee employee = this.getById(id);
        if(employee == null) {
            throw new RuntimeException("员工不存在");
        }
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        this.updateById( employee);

    }
    /**
     * 修改员工密码
     * @param passwordEditDTO
     */
    @Override
    public Result<String> updatePassword(PasswordEditDTO passwordEditDTO) {
        log.info("待修改密码员工：{}", passwordEditDTO);
        Employee employee = this.getById(BaseContext.getCurrentId());
        log.info("待修改员工id：{}",BaseContext.getCurrentId());
        if(employee == null){
            throw new RuntimeException("员工不存在");
        }
        if(employee.getStatus()==StatusConstant.DISABLE){
            return Result.error("员工账号被锁定");
        }
        if (!employee.getPassword().equals(DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes()))){
            return Result.error("原密码错误");
        }
        if(passwordEditDTO.getNewPassword().equals(passwordEditDTO.getOldPassword()) ){
            return Result.error("新密码不能与原密码相同");
        }
        employee.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        this.updateById(employee);
        return Result.success("密码修改成功");
    }


}
